package com.app.shop.controller.file;

import com.app.shop.config.security.DgbSecurityUserHelper;
import com.app.shop.controller.system.BaseController;
import com.app.shop.entity.WgPicture;
import com.app.shop.service.shop.WgPictureService;
import com.app.shop.util.ApiRest;
import com.app.shop.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.UUID;


/**
 * 图片上传
 */
@Controller
@RequestMapping(value = "/file")
public class FileLoadController extends BaseController {

    @Value("${fileUploadPath}")
    private String fileUploadPath;

    @Value("${fileHttpPath}")
    private String fileHttpPath;

    @Autowired
    WgPictureService wgPictureService;

    /**
     * 文件上传
     * @param multiReq
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/imageLoad", method = RequestMethod.POST)
    public ApiRest imgUpload(MultipartHttpServletRequest multiReq)
            throws Exception {
        try {

            MultipartFile file = multiReq.getFile("image");
            String originalFilename = System.currentTimeMillis() + file.getOriginalFilename();
            String filePathName = fileUploadPath + originalFilename;
            File localFile = new File(filePathName);

            if (!localFile.exists()) {
                localFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(
                        localFile);
                FileInputStream fs = (FileInputStream) multiReq.getFile("image").getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fs.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                fs.close();

            } else {
                logger.info("文件已存在！！");
            }
            return new ApiRest(Constant.REST_SUCCESS_CODE, Constant.SUCCESS_MESSAGE,fileHttpPath+originalFilename);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ApiRest(Constant.REST_ERROR_CODE, Constant.ERROR_MESSAGE);
    }

    /**
     * 文件上传（图片资源管理）
     * @param multiReq
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/imageLoadSrc", method = RequestMethod.POST)
    public ApiRest imageLoadSrc(MultipartHttpServletRequest multiReq)
            throws Exception {
        try {

            MultipartFile file = multiReq.getFile("file");
            String originalFilename = "tx"+System.currentTimeMillis() + file.getOriginalFilename();
            String filePathName = fileUploadPath + originalFilename;
            File localFile = new File(filePathName);

            if (!localFile.exists()) {
                localFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(
                        localFile);
                FileInputStream fs = (FileInputStream) multiReq.getFile("file").getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fs.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                fs.close();

            } else {
                logger.info("文件已存在！！");
            }
            WgPicture wgPicture= new WgPicture();
            wgPicture.setCreateUserId(DgbSecurityUserHelper.getUserInfo().getUserId());
            wgPicture.setCreatedDate(new Date());
            wgPicture.setName(originalFilename);
            wgPicture.setUrl(fileHttpPath+originalFilename);
            //将数据存储到资源库
            wgPictureService.addPicture(wgPicture);

            return new ApiRest(Constant.REST_SUCCESS_CODE, Constant.SUCCESS_MESSAGE,fileHttpPath+originalFilename);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ApiRest(Constant.REST_ERROR_CODE, Constant.ERROR_MESSAGE);
    }

}
